package com.badshun.map;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badshun.box2d.Box2DWorld;

public class GameMap {
	public TiledMap map;
	private OrthogonalTiledMapRenderer renderer;
	private OrthographicCamera camera;
	private Box2DWorld b2dWorld;
	private Body tiledBody;
	
	public static final int TILE_SIZE = 32;

	public GameMap(OrthographicCamera camera, Box2DWorld b2dWorld) {
		this.camera = camera;
		this.b2dWorld = b2dWorld;
		
		TmxMapLoader loader = new TmxMapLoader();
		map = loader.load("map/mainStage.tmx");
		
		renderer =new OrthogonalTiledMapRenderer(map);
		
		createBox2DLayer();
	}
	
	private void createBox2DLayer() {
		BodyDef bDef = new BodyDef();
		bDef.type = BodyDef.BodyType.StaticBody;
		
		PolygonShape shape = new PolygonShape();
		
		FixtureDef fDef = new FixtureDef();
		
		TiledMapTileLayer tileLayer = (TiledMapTileLayer) map.getLayers().get("obstacle");
		
		for (int i = 0; i < tileLayer.getHeight(); i++) {
			for (int j = 0; j < tileLayer.getWidth(); j++) {
				if(tileLayer.getCell(j, i) == null || tileLayer.getCell(j, i).getTile() == null) {
					continue;
				}
				
				bDef.position.set(j * TILE_SIZE + TILE_SIZE / 2, i * TILE_SIZE + TILE_SIZE  / 2);
				
				shape.setAsBox(TILE_SIZE  / 2, TILE_SIZE  / 2);
				
				fDef.shape = shape;
				fDef.filter.categoryBits = 4;
				fDef.filter.maskBits = 2 | 8;
				
				tiledBody = b2dWorld.world.createBody(bDef);
				tiledBody.createFixture(fDef);
			}
		}
	}
	
	public float getMapWidth( ) {
		return ((TiledMapTileLayer) map.getLayers().get("ground")).getWidth() * ((TiledMapTileLayer) map.getLayers().get("ground")).getTileWidth();
	}
	
	public float getMapHeight( ) {
		return ((TiledMapTileLayer) map.getLayers().get("ground")).getHeight() * ((TiledMapTileLayer) map.getLayers().get("ground")).getTileHeight();
	}

	public void render() {
		camera.update();
		
		renderer.setView(camera);
		renderer.render();
	}
}



















